package com.itheima.springbootwebtlias.aspect;

import com.itheima.springbootwebtlias.commons.CurrentHolder;
import com.itheima.springbootwebtlias.mapper.OperateLogMapper;
import com.itheima.springbootwebtlias.pojo.OperateLog;
import com.itheima.springbootwebtlias.util.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

/**
 * 记录操作日志的切面类
 */
@Slf4j
@Component
//@Aspect
public class OperationLogAspect {
    @Autowired
    private OperateLogMapper operateLogMapper;

    @Autowired
    private HttpServletRequest request; //请求数据

    //切入点表达式：execution+annotation
    @Around("execution(* com.itheima.springbootwebtlias.service.*Service.*(..)) && @annotation(com.itheima.springbootwebtlias.anno.LogOperation)")
    //通知类型：环绕通知
    public Object recordOperationLog(ProceedingJoinPoint pjp/*连接点目标方法，封装目标方法的运行信息*/) throws Throwable {
        //记录操作日志：收集操作日记信息，添加到操作日志数据表中
        long start = System.currentTimeMillis();
        Object result = pjp.proceed();
        long end = System.currentTimeMillis();
        long costTime = end - start;

        //1.定义操作日志对象，收集操作日志信息(借助环绕通知
        OperateLog operateLog = new OperateLog();
        operateLog.setOperateTime(LocalDateTime.now());//操作时间
        operateLog.setReturnValue(result+""); //返回结果
        operateLog.setCostTime(costTime); //执行耗时

        //通过连接点对象ProceedingJoinPoint，获取目标方法信息
        operateLog.setClassName(pjp.getTarget().getClass().getName()); //获取目标方法所属的类名称
        operateLog.setMethodName(pjp.getSignature().getName()); //获取目标方法名称
        operateLog.setMethodParams(Arrays.toString(pjp.getArgs())); //获取目标方法的参数
        operateLog.setOperateEmpId(CurrentHolder.getCurrentId());//操作员工id（暂时跳过）/借助JWT令牌获取用户的id信息

        //2.调用操作日志的持久层接口，添加日志信息到操作日志表中
        operateLogMapper.insert(operateLog);

        return result;
    }


}
